<template>
  <div
    @click="handleClick"
    :class="['table-caption', {isSort: column.sort, active: active }]"
    :style="columnStyle">
    {{ column.label }}
    <span v-if="column.sort" class="arrow" :class="classDirection"
    >
    </span>
  </div>
</template>

<script>
export default {
  name: 'v-th',
  props: {
    columnName: String,
    column: Object,
    active: {
      type: Boolean,
      default: false
    },
    orderBy: {
      type: Array,
      default: () => []
    },
    columnStyle: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },
  computed: {
    classDirection () {
      return this.sortDirection === 'asc'
        ? 'table-caption-sort-asc'
        : this.sortDirection === 'desc'
          ? 'table-caption-sort-desc'
          : 'table-caption-sort'
    },
    sortDirection () {
      if (this.column.sort && this.orderBy[0] && this.orderBy[0].name === this.columnName) {
        return this.orderBy[0].sort
      }
      return 'sort'
    }
  },
  methods: {
    handleClick () {
      if (this.column.sort) {
        const sortBy = [{
          name: this.columnName,
          sort: this.sortDirection === 'desc' ? 'asc' : 'desc'
        }, ...this.orderBy.filter(order => order.name !== this.columnName)]
        this.$emit('changeOrderBy', sortBy)
      }
    }
  }
}
</script>

<style scoped lang="sass">
.table-caption
  line-height: 28px
  font-weight: bold;
  &.isSort
    cursor: pointer
    .arrow
      position: relative
      top: 3px
      margin-left: 5px
    &.active
      .arrow
        opacity: 1
</style>
